<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wh:rd02:rd02:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
      <DictLabel v-if="record.bred" :dictType="'sys_red_blue'" :dictValue="record.bred" />
    </template>
    <BasicForm @register="registerForm">
      <template #rds02List>
        <a-button
          class="mb-2"
          v-if="!disabled"
          @click="handleRds02Add"
          v-auth="'wh:rd02:rd02:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <BasicTable
          @register="registerRds02Table"
          @row-click="handleRds02RowClick"
          @edit-change="rowChange"
        >
          <!-- <template #summary>
            <Table.Summary fixed>
              <Table.Summary.Row>
                <Table.Summary.Cell :index="0" :col-span="1" :style="{ textAlign: 'center' }">合计</Table.Summary.Cell>
                <Table.Summary.Cell :index="3" :col-span="4">&nbsp;</Table.Summary.Cell>
                <Table.Summary.Cell :index="10" :style="{ textAlign: 'center' }"> {{ totalIqty }}</Table.Summary.Cell>
              </Table.Summary.Row>
            </Table.Summary>
          </template> -->
        </BasicTable>
      </template>
    </BasicForm>
    <!-- <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="flow_wh_rd02"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'wh:rd02:rd02:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template> -->
    <ListSelect
      ref="listSelectRef"
      :selectList="selectListRef"
      selectType="basInvSelect"
      :queryParams="queryParams"
      :checkbox="true"
      @select="handleSelect"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWhRd02Rd02Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Rd02, rd02Save, rd02Form } from '/@/api/wms/wh/rd02/rd02';
  import { BpmButton } from '/@/components/Bpm';
  import { companyTreeData } from '/@/api/sys/company';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { basPositionTreeData } from '/@/api/bas/pos/basPosition';
  import { ListSelect } from '/@/components/ListSelect';
  import { DictLabel } from '/@/components/Dict';
  import { Table } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.rd02.rd02');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Rd02>({} as Rd02);
  const loadingRef = ref(false);
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);
  const whCode = ref<any>('');
  const disabled = ref<any>(false);
  const queryParams = ref({});

  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增出库表') : t('编辑出库表'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('出库单号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFformat: 'YYYY-MM-DD',
      },
      dynamicDisabled: true,
    },
    // {
    //   label: t('公司'),
    //   field: 'companyCode',
    //   fieldLabel: 'company.companyName',
    //   component: 'TreeSelect',
    //   componentProps: {
    //     api: companyTreeData,
    //     allowClear: true,
    //     // disabled: computed(() => disabled.value),
    //     onChange: async (e) => {
    //       queryParams.value = {
    //         companyCode: e,
    //       };
    //       let arr = await rds02Table.getDataSource();
    //       let arrNew = [...arr];
    //       arrNew.forEach(async (item, index) => {
    //         await rds02Table.deleteTableDataRecord(item);
    //       });
    //     },
    //   },
    //   required: true,
    // },
    {
      label: t('业务类型'),
      field: 'busType',
      component: 'Select',
      componentProps: {
        dictType: 'wh_rd02_bus_type',
        allowClear: true,
        disabled: computed(() => disabled.value),
        onChange: async (value) => {
          // updateSchema([
          //   {
          //     field: 'cusCode',
          //     required: value == '3' && record.value.bred =='0' ?true:false,
          //   },
          // ]);
        },
      },
      required: true,
    },
    {
      label: t('仓库'),
      field: 'whCode',
      fieldLabel: 'basWare.cwhname',
      component: 'TreeSelect',
      componentProps: {
        api: basWarehouseTreeData,
        allowClear: true,
        onChange: async (value) => {
          whCode.value = value || '-1';
          setRds02Columns();
          let arr = await rds02Table.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            let editValueRefs = item.editValueRefs;
            editValueRefs.posCode = '';
            await rds02Table.updateTableDataRecord(item.id, {
              ...item,
              posCode: '',
              // 'basPosition.posName': '',
              editValueRefs,
            });
          });
          let obj = await getFieldsValue();
          await setFieldsValue({
            ...obj,
            // defPos:''
          });
          // updateSchema([
          //   {
          //     field: 'defPos',
          //     componentProps: {
          //       params: { whcode: whCode.value },
          //     },
          //   },
          // ]);
        },
        // disabled: computed(() => disabled.value),
      },
      required: true,
    },

    // {
    //   label: t('默认货位'),
    //   field: 'defPos',
    //   fieldLabel: 'defPosition.posName',
    //   component: 'TreeSelect',
    //   componentProps: {
    //     api: basPositionTreeData,
    //     allowClear: true,
    //     canSelectParent: false,
    //     params: { whcode: whCode.value },
    //     onChange:async (value,label) => {
    //       let arr = await rds02Table.getDataSource();
    //       let arrNew = [...arr];
    //       arrNew.forEach(async (item, index) => {
    //         let editValueRefs = item.editValueRefs
    //         editValueRefs.posCode = value
    //         await rds02Table.updateTableDataRecord(item.id, {
    //             ...item,
    //             posCode: value,
    //             // 'basPosition.posName': '',
    //             editValueRefs,
    //           });
    //       });
    //     },
    //     disabled: computed(() => disabled.value),
    //   },
    //   // required: true,
    // },
    // {
    //   label: t('客户'),
    //   field: 'cusCode',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'wms_cus',
    //     allowClear: true,
    //     disabled: computed(() => disabled.value),
    //   },
    // },

    {
      label: t('红蓝标志'),
      field: 'bred',
      component: 'Select',
      componentProps: {
        dictType: 'sys_red_blue',
      },
      show: false,
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('修改人'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'Input',
      componentProps: {
        maxlength: 500,
        disabled: computed(() => disabled.value),
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('出库明细'),
      field: 'rds02List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rds02List',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 12, md: 24 },
    });

  const [registerRds02Table, rds02Table] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRds02Delete.bind(this, record),
          },
          auth: 'wh:rd02:rd02:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setRds02Columns(_res: Recordable) {
    rds02Table.setColumns([
      {
        title: t('来源ID'),
        dataIndex: 'sourceId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('来源行ID'),
        dataIndex: 'sourceDid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },

      {
        title: t('产品编码'),
        dataIndex: 'basInv.viewCode',
        width: 140,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('产品编码'),
        dataIndex: 'invCode',
        width: 140,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('产品名称'),
        dataIndex: 'basInv.invName',
        width: 160,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
      },
      {
        title: t('单位'),
        dataIndex: 'basInv.funitname',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: ({ record: record1 }) => {
          return {
            disabled: disabled.value,
            // onChange: (value, label) => {
            //   let iqty = value;
            //   if (record.value.bred == 0) {
            //     if (value > 0) {
            //       iqty = -value;
            //     }
            //   } else {
            //     if (value < 0) {
            //       iqty = -value;
            //     }
            //   }

            //   rds02Table.updateTableDataRecord(record1.id, {
            //     ...record1,
            //     iqty,
            //   });
            // },
          };
        },
        editRule: (value, _record) => {
          return new Promise((resolve, reject) => {
            if (value == 0) return reject('数量不能为0');
            if (!value || value == '') return reject('请输入数量');
            return resolve(); // 验证成功
          });
        },
        // editRule: true,
      },
      {
        title: t('货位名称'),
        dataIndex: 'posCode',
        dataLabel: 'basPosition.posName',
        width: 130,
        align: 'left',
        editRow: true,
        // editRow: computed(() => !disabled.value),
        editComponent: 'TreeSelect',
        editComponentProps: {
          disabled: disabled.value,
          api: basPositionTreeData,
          params: { whcode: whCode.value },
          allowClear: true,
          canSelectParent: false,
          immediate: true,
        },
        editRule: true,
      },
      // {
      //   title: t('形象刊'),
      //   dataIndex: 'freeVO.cfree1',
      //   width: 130,
      //   align: 'left',
      //   // editRow: true,
      //   editRow: computed(() => !disabled.value),
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 100,
      //   },
      //   editRule: false,
      // },
      {
        title: t('自由项2'),
        dataIndex: 'freeVO.cfree2',
        width: 130,
        align: 'left',
        // editRow: true,
        editRow: computed(() => !disabled.value),
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('自由项3'),
        dataIndex: 'freeVO.cfree3',
        width: 130,
        align: 'left',
        // editRow: true,
        editRow: computed(() => !disabled.value),
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        // editRow: true,
        editRow: computed(() => !disabled.value),
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
  }

  async function setRds02TableData(_res: Recordable) {
    await setRds02Columns();
    rds02Table.setTableData(record.value.rds02List || []);
  }

  async function rowChange({ column, value, record: record1 }) {
    // 输入数量
    if (column.dataIndex == 'iqty') {
      if (record.value.bred == 0) {
        if (value > 0) {
          value = -value;
        }
      } else {
        if (value < 0) {
          value = -value;
        }
      }
      record1.iqty = value;
    }
  }

  function handleRds02RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRds02Add() {
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
    // rds02Table.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handleSelect(selectData) {
    let obj = getFieldsValue();
    selectData.forEach((item, index) => {
      rds02Table.insertTableDataRecord({
        id: new Date().getTime() + index,
        isNewRecord: true,
        editable: true,
        invCode: item.invCode,
        basInv: {
          viewCode: item.viewCode,
          invName: item.invName,
          funitname: item.funitname,
          // weight: item.weight,
        },
        // cfree2: item.weight,
        posCode: obj.defPos || '',
      });
    });
  }

  function handleRds02Delete(record: Recordable) {
    rds02Table.deleteTableDataRecord(record);
  }

  async function getRds02List() {
    let rds02ListValid = true;
    let rds02List: Recordable[] = [];
    for (const record of rds02Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rds02ListValid = false;
      }
      rds02List.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rds02Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rds02List.push({
        ...record,
        status: '1',
      });
    }
    if (!rds02ListValid) {
      throw { errorFields: [{ name: ['rds02List'] }] };
    }
    return rds02List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rd02Form(data);
    record.value = (res.rd02 || {}) as Rd02;
    record.value.__t = new Date().getTime();
    whCode.value = record.value.whCode || '-1';
    queryParams.value = {};
    setFieldsValue(record.value);
    if (
      !record.value.status ||
      record.value.status == '9' ||
      record.value.status == '5' ||
      record.value.status == '6'
    ) {
      disabled.value = false;
    } else {
      disabled.value = true;
    }
    setDrawerProps({ showOkBtn: !disabled.value });
    rds02Table.setProps({
      actionColumn: {
        ifShow: !disabled.value,
        width: 60,
        actions: (record: Recordable) => [
          {
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleRds02Delete.bind(this, record),
            },
            auth: 'wh:rd02:rd02:edit',
          },
        ],
      },
    });
    setRds02TableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'whCode',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },

      // {
      //   field: 'defPos',
      //   componentProps: {
      //     params: { whcode: whCode.value },
      //   },
      // },
      // {
      //   field: 'cusCode',
      //   required: record.value.busType == '3' && record.value.bred =='0' ?true:false,
      // },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = await validate(); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      // data.status = record.value.status; // 提交状态
      data.status = '0';
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.rds02List = await getRds02List();
      // console.log('submit', params, data, record);
      const res = await rd02Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }

  const totalIqty = computed(() => {
    // 计算总报工数
    const tableData = rds02Table.getDataSource();
    console.log('tableData', tableData);
    // const tableData = getDataSource.value;
    let sum = tableData.reduce((total, item) => total + (item.iqty || 0), 0);
    return sum;
  });
</script>
